package com.pengheng.example2;

import org.bouncycastle.asn1.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ASN1EncodingAndDecodingExample {
    public static void main(String[] args) throws IOException {
        // 创建Person对象
        Person person = new Person();
        person.setName(new DERPrintableString("Ali"));
        person.setAge(new DERInteger(1));
        person.setEmail(new DERIA5String("abc@def.co"));
        Address address = new Address();
        address.setStreet(new DERPrintableString("Street"));
        address.setCity(new DERPrintableString("Man"));
        person.setAddress(address);

        // 编码Person对象为DER格式
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ASN1OutputStream oAsnOut = new ASN1OutputStream(baos);
        oAsnOut.writeObject(person);
        byte[] encoded = baos.toByteArray();

        // 将编码后的DER格式字节数组输出到控制台
        System.out.println("Encoded Person: " + bytesToHex(encoded));

        // 解码Person对象
        ByteArrayInputStream bais = new ByteArrayInputStream(encoded);
        ASN1InputStream oAsnIn = new ASN1InputStream(bais);
        DLSequence seq = (DLSequence) oAsnIn.readObject();

        // 将解码后的DER序列转换为Person对象
        DERPrintableString name = (DERPrintableString) seq.getObjectAt(0);
        ASN1Integer age = (ASN1Integer) seq.getObjectAt(1);
        DERIA5String email = (DERIA5String) seq.getObjectAt(2);
        DLSequence addressSeq = (DLSequence) seq.getObjectAt(3);
        DERPrintableString street = (DERPrintableString) addressSeq.getObjectAt(0);
        DERPrintableString city = (DERPrintableString) addressSeq.getObjectAt(1);

        Person decodedPerson = new Person();
        decodedPerson.setName(name);
        decodedPerson.setAge(age);
        decodedPerson.setEmail(email);
        Address decodedAddress = new Address();
        decodedAddress.setStreet(street);
        decodedAddress.setCity(city);
        decodedPerson.setAddress(decodedAddress);

        // 打印解码后的Person对象
        System.out.println("Decoded Person:");
        System.out.println("Name: " + decodedPerson.getName().getString());
        System.out.println("Age: " + decodedPerson.getAge().getValue());
        System.out.println("Email: " + decodedPerson.getEmail().getString());
        System.out.println("Address: ");
        System.out.println("Street: " + decodedPerson.getAddress().getStreet().getString());
        System.out.println("City: " + decodedPerson.getAddress().getCity().getString());
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            builder.append(String.format("%02X", b));
        }
        return builder.toString();
    }
}